package cn.stylefeng.guns.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.core.pojo.response.ErrorResponseData;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.core.pojo.response.SuccessResponseData;
import cn.stylefeng.guns.core.util.Md5Util;
import cn.stylefeng.guns.core.util.RedisUtil;
import cn.stylefeng.guns.sys.core.jwt.JwtPayLoad;
import cn.stylefeng.guns.sys.core.jwt.JwtTokenUtil;
import cn.stylefeng.guns.user.entity.User;
import cn.stylefeng.guns.user.mapper.UserMapper;
import cn.stylefeng.guns.user.service.UserService;
import cn.stylefeng.guns.user.enums.UserExceptionEnum;
import cn.stylefeng.guns.user.dto.UserDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * user 服务实现类
 *
 * @author aria
 * @date 2021/02/20 20:24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static String defaultImgUrl = "http://xinguan-parent-416.oss-cn-beijing.aliyuncs.com/2021/03/02/f80233f9f9c6462c9b11f67aadfd60ab.png";
    private static String defaultNick = "新用户";

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public PageResult<User> page(UserDTO userDTO) {

        // 构造条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        // 拼接查询条件-
        if (userDTO != null && ObjectUtil.isNotEmpty(userDTO.getUserId())) {
            queryWrapper.like(User::getUserId, userDTO.getUserId());
        }

        // 拼接查询条件-
        if (userDTO != null && ObjectUtil.isNotEmpty(userDTO.getUserName())) {
            queryWrapper.like(User::getUserName, userDTO.getUserName());
        }

        // 查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<User> list() {

        // 构造条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        return this.list(queryWrapper);
    }

    @Override
    public User add(UserDTO userDTO) {
        //查重
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userDTO.getUserName());
        User users = this.baseMapper.selectOne(queryWrapper);
        if (users != null) {
            return null;
        }

        // 将dto转为po实体
        User user = new User();
        BeanUtil.copyProperties(userDTO, user);
        //密码加密
        String md5Password = Md5Util.encodeByMD5(user.getPassword());
        user.setPassword(md5Password);
        //如果生日为空
        if (ObjectUtil.isEmpty(user.getBirthday())) {
            user.setBirthday(new Date());
        }
        //如果照片地址为空
        if (ObjectUtil.isEmpty(user.getUserImage())) {
            user.setUserImage(defaultImgUrl);
        }
        //如果昵称为空
        if (ObjectUtil.isEmpty(user.getNick())) {
            user.setNick(defaultNick);
        }
        if (ObjectUtil.isEmpty(user.getPower())) {
            user.setPower(0);
        }
        if (ObjectUtil.isEmpty(user.getSex())) {
            user.setSex(1);
        }
        if (ObjectUtil.isEmpty(user.getAddress())) {
            user.setAddress("未知");
        }
        this.save(user);
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(UserDTO userDTO) {
        this.removeById(userDTO.getUserId());
    }

    @Override
    public void edit(UserDTO userDTO) {

        // 根据id查询实体,并将DTO转换成PO
        User user = this.queryUser(userDTO);

        if (!ObjectUtil.isEmpty(userDTO.getNick())) {
            user.setNick(userDTO.getNick());
        }
        if (!ObjectUtil.isEmpty(userDTO.getBirthday())) {
            user.setBirthday(userDTO.getBirthday());
        }
        if (!ObjectUtil.isEmpty(userDTO.getPassword())) {
            user.setPassword(userDTO.getPassword());
        }
        if (!ObjectUtil.isEmpty(userDTO.getSex())) {
            user.setSex(userDTO.getSex());
        }
        if (!ObjectUtil.isEmpty(userDTO.getPower())) {
            user.setNick(userDTO.getNick());
        }
        if (!ObjectUtil.isEmpty(userDTO.getUserImage())) {
            user.setUserImage(userDTO.getUserImage());
        }
        if (!ObjectUtil.isEmpty(userDTO.getUserName())) {
            user.setUserName(userDTO.getUserName());
        }

        this.updateById(user);
    }

    @Override
    public User detail(UserDTO userDTO) {
        return this.queryUser(userDTO);
    }

    @Override
    public ResponseData Load(String userName, String password) {
        User user = null;
        String md5Password = Md5Util.encodeByMD5(password);
        // 构造条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, userName);
        queryWrapper.eq(User::getPassword, md5Password);
        user = this.getOne(queryWrapper);
        //未查到用户
        if (ObjectUtil.isEmpty(user)) {
            return new ErrorResponseData(400, "账号或密码错误");
        }
        //创建token
        JwtPayLoad jwtPayLoad = new JwtPayLoad(Long.valueOf(user.getUserId()),user.getUserName());
        String token = JwtTokenUtil.generateToken(jwtPayLoad);
        //token写入redis
        redisUtil.add(user.getUserName(),token);
        return new SuccessResponseData(token);
    }

    @Override
    public ResponseData adminLogin(UserDTO userDTO) {
        User sqlUser = null;
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, userDTO.getUserName());
        queryWrapper.eq(User::getPassword, userDTO.getPassword());
        sqlUser = this.getOne(queryWrapper);
        //未查到用户
        if (ObjectUtil.isEmpty(sqlUser)) {
            return new ErrorResponseData(400, "账号或密码错误");
        }
        if (sqlUser.getPower() <= 0) {
            return new ErrorResponseData(400, "您没有权限");
        }
        return new SuccessResponseData(sqlUser);
    }


    /**
     * 获取user
     *
     * @author aria
     * @since 2021/02/20 20:24
     */
    private User queryUser(UserDTO userDTO) {
        User user = this.getById(userDTO.getUserId());
        if (ObjectUtil.isEmpty(user)) {
            throw new ServiceException(UserExceptionEnum.NOT_EXISTED);
        }
        return user;
    }
}